<template>
  <div class="trend-charts">
    <el-card class="mb-4" shadow="never">
      <el-form :inline="true" size="small">
        <el-form-item label="趋势类型">
          <el-select v-model="trendType" style="width:160px">
            <el-option label="领料趋势" value="pick"/>
            <el-option label="合格率趋势" value="pass"/>
            <el-option label="供应商绩效趋势" value="supplier"/>
          </el-select>
        </el-form-item>
        <el-form-item label="统计周期">
          <el-select v-model="period" style="width:100px">
            <el-option label="周" value="week"/>
            <el-option label="月" value="month"/>
            <el-option label="年" value="year"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="exportExcel">导出Excel</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 图表 -->
    <el-card>
      <div ref="chartRef" style="width:100%;height:360px"></div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch, computed } from 'vue'
import * as echarts from 'echarts'
import * as XLSX from 'xlsx'
import { ElMessage } from 'element-plus'

const trendType = ref('pick')
const period = ref('month')

// ---------- 模拟数据生成 ----------
function genDates(period, count) {
  const now = new Date()
  let arr = []
  for(let i=count-1;i>=0;i--){
    let d = new Date(now)
    if(period==='week') d.setDate(now.getDate()-i*7)
    else if(period==='month') d.setMonth(now.getMonth()-i)
    else if(period==='year') d.setFullYear(now.getFullYear()-i)
    if(period==='year') arr.push(d.getFullYear()+'年')
    else if(period==='month') arr.push(d.getFullYear()+'-'+String(d.getMonth()+1).padStart(2,'0'))
    else arr.push((d.getMonth()+1)+'/'+d.getDate())
  }
  return arr
}

// 领料趋势：按周期统计各物料的领料量
function genPickData(period) {
  const labels = genDates(period, period==='year'?5:period==='month'?12:8)
  const mats = ['对乙酰氨基酚','头孢拉定','葡萄糖','乳糖']
  let data = []
  for(let m of mats){
    data.push({
      name: m,
      data: labels.map(()=>Math.floor(Math.random()*3000)+200)
    })
  }
  return { labels, data }
}

// 合格率趋势：按周期统计产品合格率
function genPassData(period) {
  const labels = genDates(period, period==='year'?5:period==='month'?12:8)
  return {
    labels,
    data: [{
      name: '合格率',
      data: labels.map(()=> (Math.random()*8+90).toFixed(2) )
    }]
  }
}

// 供应商绩效趋势：按周期统计供应商准时交付率
function genSupplierData(period) {
  const labels = genDates(period, period==='year'?5:period==='month'?12:8)
  const sups = ['国药集团','恒瑞医药','华润药业','复星医药']
  let data = []
  for(let s of sups){
    data.push({
      name: s,
      data: labels.map(()=> (Math.random()*5+92).toFixed(2) )
    })
  }
  return { labels, data }
}

// 数据选取
const chartData = computed(()=>{
  if(trendType.value==='pick') return genPickData(period.value)
  if(trendType.value==='pass') return genPassData(period.value)
  if(trendType.value==='supplier') return genSupplierData(period.value)
  return {labels:[],data:[]}
})

// ---------- ECharts 绘制 ----------
const chartRef = ref()
let chartIns = null
function chartOption() {
  if(trendType.value==='pick'){
    // 多物料柱状图
    return {
      title: { text: '领料趋势', left: 18, top: 18, textStyle: { fontSize: 15 }},
      tooltip: { trigger: 'axis' },
      legend: { top: 38 },
      grid: { left: 60, right: 30, bottom: 40, top: 80 },
      xAxis: { type: 'category', data: chartData.value.labels },
      yAxis: { type: 'value', name: '领料量' },
      series: chartData.value.data.map((s,i)=>({
        name: s.name,
        type: 'bar',
        stack: false,
        barMaxWidth: 36,
        data: s.data
      }))
    }
  }
  if(trendType.value==='pass'){
    // 单线折线图
    return {
      title: { text: '合格率趋势', left: 18, top: 18, textStyle: { fontSize: 15 }},
      tooltip: { trigger: 'axis' },
      grid: { left: 60, right: 30, bottom: 40, top: 60 },
      xAxis: { type: 'category', data: chartData.value.labels },
      yAxis: { type: 'value', name: '合格率(%)', min:90, max:100 },
      series: [{
        name: '合格率',
        type: 'line',
        data: chartData.value.data[0].data,
        symbol: 'circle',
        symbolSize: 10,
        lineStyle: { width: 3, color: '#49B1F5' },
        itemStyle: { color: '#49B1F5' },
        areaStyle: { opacity: 0.13 }
      }]
    }
  }
  if(trendType.value==='supplier'){
    // 多供应商折线
    return {
      title: { text: '供应商准时交付率', left: 18, top: 18, textStyle: { fontSize: 15 }},
      tooltip: { trigger: 'axis' },
      legend: { top: 38 },
      grid: { left: 60, right: 30, bottom: 40, top: 80 },
      xAxis: { type: 'category', data: chartData.value.labels },
      yAxis: { type: 'value', name: '准时率(%)', min:90, max:100 },
      series: chartData.value.data.map((s,i)=>({
        name: s.name,
        type: 'line',
        data: s.data,
        symbol: 'circle',
        symbolSize: 10,
        lineStyle: { width: 3 },
        areaStyle: { opacity: 0.09 }
      }))
    }
  }
  return {}
}
function drawChart(){
  if(!chartRef.value) return
  if(!chartIns) chartIns = echarts.init(chartRef.value)
  chartIns.setOption(chartOption(), true)
  chartIns.resize()
}
onMounted(()=>{ nextTick(drawChart) })
watch([trendType,period], ()=>{ nextTick(drawChart) })

// ---------- 导出Excel ----------
function exportExcel(){
  // 按当前图表数据导出
  const heads = ['周期', ...chartData.value.data.map(d=>d.name)]
  const body = chartData.value.labels.map((label,i)=>[
    label,
    ...chartData.value.data.map(d=>d.data[i])
  ])
  const ws = XLSX.utils.aoa_to_sheet([heads, ...body])
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '趋势分析')
  XLSX.writeFile(wb, '趋势分析图表.xlsx')
  ElMessage.success('已导出Excel')
}
</script>

<style scoped>
.trend-charts {
  padding: 20px 16px;
}
.mb-4 { margin-bottom: 16px; }
</style>
